<?php

namespace App\Models\Sys;

use Exception;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Role extends Model
{
    protected $table = 'sys_role';

    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s',
    ];
    //获取所有用户
    public function getAllRole($param)
    {
        if(isset($param['isPaging']) && $param['isPaging']){
            return $this->where('forbidden','!=',1)->get();
        }
        $pageSize = $param['size'] ?? 10;
        return $this->paginate($pageSize);
    }


    public function saveMenu($id, array $menu)
    {
        $Permission = new Permission();
        $data = $Permission->getAllPermission(false);
        $ids = [];
        $insertData = [];
        foreach ($menu as $v) {
            if ($data[$v]['parent_id'] != 0) {
                $ids[] = $data[$v]['parent_id'];
            }
            $ids[] = $v;
        }
        $ids = array_unique($ids);
        foreach ($ids as $v) {
            $insertData[] = [
                'role_id' => $id,
                'menu_id' => $v
            ];
        }
        DB::beginTransaction();
        try {
            DB::table('sys_role_menu')->where('role_id', '=', $id)->delete();
            DB::table('sys_role_menu')->insert($insertData);
            DB::commit();
            return true;
        } catch (Exception $e) {
            // return $e->getMessage();
            DB::rollBack();
            return false;
        }
    }
}
